#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
登录标签页
"""

from PySide6.QtCore import Qt
from PySide6.QtWidgets import (
    QWidget, QVBoxLayout, QFormLayout, QLineEdit,
    QPushButton, QLabel, QCheckBox, QTextEdit
)

from src.ui.base_window import BaseWindow


class LoginTab(BaseWindow):
    """登录标签页"""
    
    def __init__(self, config, client, token_view):
        super().__init__()
        self.config = config
        self.client = client
        self.token_view = token_view  # 不再使用，但为了兼容性保留参数
        self.login_token_view = None  # 登录标签页本地的Token显示区域
        self.username_edit = None
        self.password_edit = None
        self.test_account_checkbox = None
        
    def build_ui(self) -> QWidget:
        """构建UI界面"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        # 登录表单
        form_group = self._create_login_form()
        layout.addWidget(form_group)
        
        # 登录按钮
        login_btn = QPushButton("登录")
        login_btn.clicked.connect(self.on_login)
        login_btn.setStyleSheet("""
            QPushButton {
                background-color: #2196F3;
                color: white;
                padding: 8px 20px;
                border: none;
                border-radius: 3px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #0b7dda;
            }
        """)
        layout.addWidget(login_btn, alignment=Qt.AlignmentFlag.AlignLeft)
        
        # Token显示区域
        token_group = self._create_token_display_group()
        layout.addWidget(token_group)
        
        # 结果输出区域
        layout.addWidget(QLabel("结果输出："))
        self.result_view = self.create_result_view()
        layout.addWidget(self.result_view)
        
        layout.addStretch()
        return widget
        
    def _create_login_form(self) -> QWidget:
        """创建登录表单"""
        group = QWidget()
        group.setStyleSheet("""
            QWidget {
                border: 1px solid #ccc;
                border-radius: 5px;
                padding: 15px;
                margin: 5px;
            }
        """)
        
        layout = QFormLayout(group)
        
        # 测试账号开关
        self.test_account_checkbox = QCheckBox("使用测试账号")
        self.test_account_checkbox.stateChanged.connect(self.on_toggle_test_account)
        layout.addRow(self.test_account_checkbox)
        
        # 用户名输入
        self.username_edit = QLineEdit()
        self.username_edit.setPlaceholderText("用户名")
        self.username_edit.setMinimumWidth(500)  # 增加用户名输入框宽度
        self.username_edit.setStyleSheet("""
            QLineEdit {
                padding: 8px;
                font-size: 14px;
                border: 2px solid #ccc;
                border-radius: 4px;
            }
            QLineEdit:focus {
                border-color: #2196F3;
            }
        """)
        layout.addRow("用户名：", self.username_edit)
        
        # 密码输入
        self.password_edit = QLineEdit()
        self.password_edit.setEchoMode(QLineEdit.EchoMode.Password)
        self.password_edit.setPlaceholderText("密码")
        self.password_edit.setMinimumWidth(500)  # 增加密码输入框宽度
        self.password_edit.setStyleSheet("""
            QLineEdit {
                padding: 8px;
                font-size: 14px;
                border: 2px solid #ccc;
                border-radius: 4px;
            }
            QLineEdit:focus {
                border-color: #2196F3;
            }
        """)
        layout.addRow("密码：", self.password_edit)
        
        return group
        
    def _create_token_display_group(self) -> QWidget:
        """创建Token显示组"""
        group = QWidget()
        group.setStyleSheet("""
            QWidget {
                border: 1px solid #ccc;
                border-radius: 5px;
                padding: 10px;
                margin: 5px;
            }
        """)
        
        layout = QVBoxLayout(group)
        layout.addWidget(QLabel("JWT Token："))
        
        # 创建本地Token显示区域
        self.login_token_view = QTextEdit()
        self.login_token_view.setReadOnly(True)
        self.login_token_view.setMaximumHeight(100)
        self.login_token_view.setPlaceholderText("登录后JWT Token将显示在这里...")
        self.login_token_view.setStyleSheet("""
            QTextEdit {
                background-color: #f0f8ff;
                border: 2px solid #2196F3;
                border-radius: 5px;
                font-family: 'Courier New', monospace;
                font-size: 12px;
                color: #333;
                padding: 8px;
            }
        """)
        layout.addWidget(self.login_token_view)
        
        return group
        
    def on_toggle_test_account(self, state: int):
        """切换测试账号开关"""
        if state:  # 选中状态
            test_account = self.config.get_test_account()
            self.username_edit.setText(test_account["username"])
            self.password_edit.setText(test_account["password"])
            self.print_result("测试账号", {"status": "loaded", "account": test_account})
        else:  # 未选中状态
            self.username_edit.clear()
            self.password_edit.clear()
            self.print_result("测试账号", {"status": "cleared"})
            
    def on_login(self):
        """处理登录"""
        # 验证必填字段
        fields = {
            'username': self.username_edit,
            'password': self.password_edit
        }
        field_names = {
            'username': '用户名',
            'password': '密码'
        }
        
        if not self.validate_required_fields(fields, field_names):
            return
            
        if not self.client.base_url:
            self.show_warning("未配置站点地址", "请先在“站点设置”中保存 WordPress 站点地址")
            return
            
        username = self.username_edit.text().strip()
        password = self.password_edit.text()
        
        ok, data = self.client.login(username, password)
        if ok:
            # 调试信息：打印返回的数据结构
            print(f"登录成功，返回数据: {data}")
            
            # 尝试从返回数据中获取token
            token: str = data.get("token", "")
            
            # 如果返回数据中没有token，尝试从客户端获取
            if not token:
                token = self.client.get_token() or ""
                print(f"从客户端获取token: {token}")
            
            print(f"最终token值: {token}")
            
            if token:
                # 只在本地显示Token
                self.login_token_view.setPlainText(token)
                self.show_message("登录成功", "JWT Token 已获取")
                self.print_result("登录成功", {"token": token[:20] + "..." if len(token) > 20 else token})
            else:
                self.show_warning("登录异常", "登录成功但未获取到Token")
                self.print_result("登录异常", {"error": "登录成功但未获取到Token", "data": data})
        else:
            # 只清空本地Token显示区域
            self.login_token_view.setPlainText("")
            self.print_result("登录失败", data)